package com.base.controller;

import java.io.PrintWriter;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import com.base.comm.CommContent;
import com.base.po.voip.SelfShop;
import com.base.po.voip.SelfShopCategory;
import com.base.po.voip.SelfShopGoods;
import com.base.po.voip.Users;
import com.base.service.LogsService;
import com.base.service.SelfShopCategoryService;
import com.base.service.SelfShopGoodsService;
import com.base.service.SelfShopService;
import com.base.service.UsersService;
import com.base.utils.DatabaseUtil;
import com.base.utils.IP;
import com.base.utils.Produce;

@Controller
@RequestMapping("/admin")
public class update_SelfShopGoods {
	@Autowired
	private LogsService logsService;// log日志
	@Autowired
	private SelfShopService selfShopService;
	@Autowired
	private SelfShopCategoryService selfShopCategoryService;
	@Autowired
	private SelfShopGoodsService selfShopGoodsService;
	@Autowired
	private UsersService usersService;

	// 账户信息
	@RequestMapping("/update_SelfShopGoods")
	public ModelAndView index(HttpServletRequest request, @RequestParam(value = "id", required = true) String id)
			throws Exception {
		// 返回ModelAndView
		ModelAndView modelAndView = new ModelAndView();
		if (id == null) {
			modelAndView.setViewName("jsp/datanotfound");
			return modelAndView;
		}
		SelfShopGoods selfShopGoods = selfShopGoodsService.selectById(id);
		if (selfShopGoods == null || selfShopGoods.getId() == null) {
			modelAndView.setViewName("jsp/datanotfound");
			return modelAndView;
		}

		String adminUserId = (String) request.getSession().getAttribute("adminUserId");
		Users users = usersService.selectByPrimaryKey(adminUserId);
		// 获取自建商城分类信息
		List<SelfShopCategory> selfShopCategory = null;
		if(users.getRole() == 0 || users.getRole() == 1) {
			selfShopCategory = selfShopCategoryService.selectByLevel1(adminUserId,adminUserId);
			request.setAttribute("userId", adminUserId);
		}
		if(users.getRole() == 2) {
			selfShopCategory = selfShopCategoryService.selectByLevel1(users.getParentid(), users.getParentid());
			request.setAttribute("userId", users.getParentid());
		}

		// 获取自建商城信息
		List<SelfShop> selfShops = null;
		SelfShop selfShop = null;
		if(users.getRole() == 0 || users.getRole() == 1) {
			selfShops = selfShopService.selectBySelfShop(adminUserId,adminUserId);
		}
		if(users.getRole() == 2) {
			selfShops = selfShopService.selectBySelfShop(users.getParentid(),adminUserId);
		}
		if(selfShops != null && selfShops.size() > 0) {
			selfShop = selfShops.get(0);
		}

		// 发布商信息
		Users shop = usersService.selectByPrimaryKey(selfShopGoods.getAccount());
		if(shop != null) {
			selfShopGoods.setAccount(shop.getUsername());
		}

		request.setAttribute("selfShopCategory", selfShopCategory);
		request.setAttribute("selfShopGoods", selfShopGoods);
		request.setAttribute("selfShop", selfShop);
		request.setAttribute("userId", adminUserId);


		if (adminUserId == null) {
			modelAndView.setViewName("jsp/login");
		} else {
			modelAndView.setViewName("jsp/update_SelfShopGoods");
		}
		return modelAndView;
	}

	String SUCCESS = "success";

	// 更改商户信息
    /**
     *  修改商品信息
     * @param request
     * @param response
     * @param obj
     * @throws Exception
     */
	@RequestMapping(value = "/updateSelfGoodsByJson", method = RequestMethod.POST)
	public   void  updateSelfGoodsByJson(HttpServletRequest request, HttpServletResponse response,@RequestBody JSONObject obj) throws Exception {
        try {
            String id = obj.get("id").toString();
            String goodstext = obj.getString("goodstext");
            String showpic = obj.getString("showpic");
            String detailpic1 = obj.getString("detailpic1");
            String detailpic2 = obj.getString("detailpic2");
            String detailpic3 = obj.getString("detailpic3");
            String detailpic4 = obj.getString("detailpic4");
            String detailvideo = obj.getString("detailvideo");
            String firstclassify = obj.getString("firstclassify");
            String secondclassify = obj.getString("secondclassify");
            BigDecimal price = new BigDecimal(Double.parseDouble(obj.get("price").toString()));
            BigDecimal memberprice = new BigDecimal(0);
            try {
                memberprice = new BigDecimal(Double.parseDouble(obj.get("memberprice").toString()));
            } catch (Exception e) {
                memberprice = null;
            }
            BigDecimal derate = new BigDecimal(Double.parseDouble(obj.getString("derate")));
            String introduce = URLDecoder.decode(obj.getString("introduce"), "UTF-8");
            String context = obj.getString("context");
            String standard = obj.getString("standard");
            String account = obj.getString("account");
            String exchange = obj.getString("exchange");
            Integer stock = Integer.parseInt(obj.getString("stock"));
            String detailslink = obj.getString("detailslink");
            String supplier = obj.getString("supplier");
            String color = obj.getString("color");
            String size = obj.getString("size");
            context = URLDecoder.decode(context, "UTF-8");
            // 返回参数
            response.setCharacterEncoding("utf-8");
            response.setContentType("text/html;charset=UTF-8");
//		String adminUserId = (String) request.getSession().getAttribute("adminUserId");

            SelfShopGoods selfShopGoods = selfShopGoodsService.selectById(id);
            PrintWriter out = response.getWriter();


            if (showpic != null && showpic != "undefined" && !showpic.equals("")) {
                selfShopGoods.setShowpic(showpic);
            }
            if (detailpic1 != null && detailpic1 != "undefined" && !detailpic1.equals("")) {
                selfShopGoods.setDetailpic1(detailpic1);
            }
            if (detailpic2 != null && detailpic2 != "undefined" && !detailpic2.equals("")) {
                selfShopGoods.setDetailpic2(detailpic2);
            }
            if (detailpic3 != null && detailpic3 != "undefined" && !detailpic3.equals("")) {
                selfShopGoods.setDetailpic3(detailpic3);
            }
            if (detailpic4 != null && detailpic4 != "undefined" && !detailpic4.equals("")) {
                selfShopGoods.setDetailpic4(detailpic4);
            }
            if (detailvideo != null && detailvideo != "undefined" && !detailvideo.equals("")) {
                selfShopGoods.setDetailvideo(detailvideo);
            }


            int code = 0;

            if (firstclassify != null && !firstclassify.equals("undefined") && !firstclassify.equals("0")) {
                SelfShopCategory firstCategory = selfShopCategoryService.selectByPrimaryKey(firstclassify);
                if (firstCategory != null) {
                    firstclassify = firstCategory.getId();
                } else {
                    out.print("未找到对应一级分类");
                    return;
                }
            } else {
                firstclassify = null;
            }

            if (secondclassify != null && !secondclassify.equals("undefined") && !secondclassify.equals("0")) {
                SelfShopCategory secondCategory = selfShopCategoryService.selectByPrimaryKey(secondclassify);
                if (secondCategory != null) {
                    secondclassify = secondCategory.getId();
                } else {
                    out.print("未找到对应二级分类");
                    return;
                }
            } else {
                secondclassify = null;
            }

            List<Users> shop = null;
            if (account != null && !account.equals("undefined")) {
                shop = usersService.selectByUserName(account);
                if (shop != null && shop.size() > 0) {
                    account = shop.get(0).getId();
                }
            }
            selfShopGoods.setGoodstext(goodstext);
            selfShopGoods.setFirstclassify(firstclassify);
            selfShopGoods.setSecondclassify(secondclassify);
            selfShopGoods.setPrice(price);
            selfShopGoods.setMemberprice(memberprice);
            selfShopGoods.setDerate(derate);
            selfShopGoods.setAccount(account);
            selfShopGoods.setIntroduce(introduce);
            selfShopGoods.setContext(context);
            selfShopGoods.setStandard(standard);
            selfShopGoods.setExchange(exchange);
            selfShopGoods.setDetailslink(detailslink);
            selfShopGoods.setStock(stock);
            selfShopGoods.setSupplier(supplier);
            selfShopGoods.setColor(color);
            selfShopGoods.setSize(size);
            if (id == null) {
                out.print("浏览器在点击的过程中发现丢失了用户信息，请您刷新重试！");
                return;
            } else {
                code = selfShopGoodsService.updateByPrimaryKeySelective(selfShopGoods);
                String usernamesys = (String) request.getSession().getAttribute("useracc");
                if (code == 1) {
                    logsService.insert(CommContent.TYPE_UPDATE, "修改" + goodstext + "商品信息成功", usernamesys, true,
                            IP.getIpAddr(request));
                    out.print(SUCCESS);
                } else {
                    logsService.insert(CommContent.TYPE_UPDATE, "修改" + goodstext + "商品信息失败", usernamesys, true,
                            IP.getIpAddr(request));
                    out.print("更改失败，请您重试");
                }
            }
        }catch (JSONException e){
            PrintWriter out = response.getWriter();
            out.print("数据传入有误，检查数据");
        }
    }
	// 更改商户信息
	@RequestMapping(value = "/updateSelfGoods", method = RequestMethod.POST)
	public void updateSelfGoods(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "id", required = true) String id, String goodstext, String showpic, String detailpic1, String detailpic2,
			String detailpic3, String detailpic4, String detailvideo, String firstclassify, String secondclassify,
			BigDecimal price, BigDecimal derate, String introduce, String context, String standard, Byte status,
			Byte datastatus, String opentime, String account,Integer choose, String exchange, Integer stock,
			String detailslink, String supplier, String color, String size) throws Exception {
		// 返回参数
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=UTF-8");
//		String adminUserId = (String) request.getSession().getAttribute("adminUserId");

		SelfShopGoods selfShopGoods = selfShopGoodsService.selectById(id);
		PrintWriter out = response.getWriter();

		if(context != null && context != "undefined" && !context.equals("")) {
			if(context.length() > DatabaseUtil.getFieldCapacity()) {
				out.print("商品详情添加的图片过大");
				return;
			}
		}

		if(showpic != null && showpic != "undefined" && !showpic.equals("")) {
			selfShopGoods.setShowpic(showpic);
		}
		if(detailpic1 != null && detailpic1 != "undefined" && !detailpic1.equals("")) {
			selfShopGoods.setDetailpic1(detailpic1);
		}
		if(detailpic2 != null && detailpic2 != "undefined" && !detailpic2.equals("")) {
			selfShopGoods.setDetailpic2(detailpic2);
		}
		if(detailpic3 != null && detailpic3 != "undefined" && !detailpic3.equals("")) {
			selfShopGoods.setDetailpic3(detailpic3);
		}
		if(detailpic4 != null && detailpic4 != "undefined" && !detailpic4.equals("")) {
			selfShopGoods.setDetailpic4(detailpic4);
		}
		if(detailvideo != null && detailvideo != "undefined" && !detailvideo.equals("")) {
			selfShopGoods.setDetailvideo(detailvideo);
		}


		int code = 0;
		if(choose != null) {
			if(choose == 1) {
				selfShopGoods.setDetailpic1("");
				System.out.println(selfShopGoods.getDetailpic1());
			}
			if(choose == 2) {
				selfShopGoods.setDetailpic2("");
			}
			if(choose == 3) {
				selfShopGoods.setDetailpic3("");
			}
			if(choose == 4) {
				selfShopGoods.setDetailpic4("");
			}
			code = selfShopGoodsService.updateByPrimaryKeySelective(selfShopGoods);
		}

		if(firstclassify != null && !firstclassify.equals("undefined") && !firstclassify.equals("0")) {
			SelfShopCategory firstCategory = selfShopCategoryService.selectByPrimaryKey(firstclassify);
			if(firstCategory != null) {
				firstclassify = firstCategory.getId();
			}else {
				out.print("未找到对应一级分类");
				return;
			}
		}else {
			firstclassify = null;
		}

		if(secondclassify != null && !secondclassify.equals("undefined") && !secondclassify.equals("0")) {
			SelfShopCategory secondCategory = selfShopCategoryService.selectByPrimaryKey(secondclassify);
			if(secondCategory != null) {
				secondclassify = secondCategory.getId();
			}else {
				out.print("未找到对应二级分类");
				return;
			}
		}else {
			secondclassify = null;
		}

		List<Users> shop = null;
		if(account != null && !account.equals("undefined")) {
			shop = usersService.selectByUserName(account);
			if(shop != null && shop.size() > 0) {
				account = shop.get(0).getId();
			}
		}

		selfShopGoods.setGoodstext(goodstext);
		selfShopGoods.setFirstclassify(firstclassify);
		selfShopGoods.setSecondclassify(secondclassify);
		selfShopGoods.setPrice(price);
		selfShopGoods.setDerate(derate);
		selfShopGoods.setAccount(account);
		selfShopGoods.setIntroduce(introduce);
		selfShopGoods.setContext(context);
		selfShopGoods.setStandard(standard);
		selfShopGoods.setStatus(status);
		selfShopGoods.setExchange(exchange);
		selfShopGoods.setDetailslink(detailslink);
		selfShopGoods.setStock(stock);
		selfShopGoods.setDatastatus(datastatus);
		selfShopGoods.setSupplier(supplier);
		selfShopGoods.setColor(color);
		selfShopGoods.setSize(size);
		if(opentime != null && opentime.equals("1")) {
			selfShopGoods.setShelftime(Produce.getNowDate());
		}
		if (id == null) {
			out.print("浏览器在点击的过程中发现丢失了用户信息，请您刷新重试！");
			return;
		} else {
			code = selfShopGoodsService.updateByPrimaryKeySelective(selfShopGoods);
			String usernamesys = (String) request.getSession().getAttribute("useracc");
			if (code == 1) {
				logsService.insert(CommContent.TYPE_UPDATE, "修改" + goodstext + "商品信息成功", usernamesys, true,
						IP.getIpAddr(request));
				out.print(SUCCESS);
			} else {
				logsService.insert(CommContent.TYPE_UPDATE, "修改" + goodstext + "商品信息失败", usernamesys, true,
						IP.getIpAddr(request));
				out.print("更改失败，请您重试");
			}
		}
	}
}
